package com.xdf.vpndialer.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class VpnDialer {

    @Value("${centosvpn.network}")
    private String network;

    @Value("${centosvpn.account}")
    private String account;

    @Value("${centosvpn.pass}")
    private String pass;

    @Autowired
    private ExecExtFile execExtFile;

    public static boolean isOnLine() throws Exception {
        String ret = executeCmd("ping 172.17.0.9");
        if( ret.length()<=0 ) return false;
        int index = ret.indexOf("请求超时");
        return index>=0?false:true;
    }

    public void connectVPN() throws Exception {
        if( isOnLine() == false ){
            log.info("检测到离线，开始断开连接");
            cutAdsl(network);
            log.info("开始重新拨号：" + network + "," + account + "," + pass);
            connAdsl(network,account, pass);
//            dialerVPN();
        }
        else {
            log.info("已经在线，不会重新拨号！");
        }
    }

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //connectVPN();
        //System.out.println(executeCmd("ping 172.17.0.111"));
        //connAdsl("centos7VPN","chanchaw", "7758chanchaw");
//        Thread.sleep(1000);
//        cutAdsl("VPN_Test");
//        Thread.sleep(1000);
    }

    /**
     * 执行CMD命令,并返回String字符串
     */
    public static String executeCmd(String strCmd) throws Exception {
        log.info("executeCmd内执行的命令是：cmd /c " + strCmd);
        Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);
        StringBuilder sbCmd = new StringBuilder();
        //这里很重要，设置GB2312解决乱码！！！
        //如果程序默认编码就是GB2312，可以不写
        //我NetBeans默认用UTF8
//        BufferedReader br = new BufferedReader(new InputStreamReader(p
//                .getInputStream(), "GB2312"));
        BufferedReader br = new BufferedReader(new InputStreamReader(p
                .getInputStream()));
        String line;

        List<String> retString = new ArrayList<>();
        int i = 0;
        while ((line = br.readLine()) != null) {
            retString.add(line);
            sbCmd.append(line + "\n");
        }

        log.info("拨号中返回的信息：" + retString.toString());
        return sbCmd.toString();

        /*
        //如果整个过程换成这样，就更清楚了。getInputStream是获取最原始的字节流，
        //cmd返回的是以GB2312双字节编码的字节流
        InputStream in = p.getInputStream();
        byte[] b = new byte[2000];
        in.read(b);
        String msg = new String(b, "GB2312");
        //用GB2312解释这堆字节，就可以组装成一个正常的String了
        //如果上边不写GB2312，等于这里用UTF8组装，结果一样
        return msg;
        */
    }

    public static String executeCmd1(String strCmd) throws Exception {
        Process p = Runtime.getRuntime().exec("cmd /c " + strCmd);


//        StringBuilder sbCmd = new StringBuilder();
//        BufferedReader br = new BufferedReader(new InputStreamReader(p
//                .getInputStream(), "GB2312"));
//        String line;
//
//        List<String> retString = new ArrayList<>();
//        int i = 0;
//        while ((line = br.readLine()) != null) {
//            retString.add(line);
//            sbCmd.append(line + "\n");
//        }
//
//        log.info("拨号中返回的信息：" + retString.toString());
//        return sbCmd.toString();


        //如果整个过程换成这样，就更清楚了。getInputStream是获取最原始的字节流，
        //cmd返回的是以GB2312双字节编码的字节流
        InputStream in = p.getInputStream();
        byte[] b = new byte[2000];
        in.read(b);
        String msg = new String(b, "GB2312");
        //用GB2312解释这堆字节，就可以组装成一个正常的String了
        //如果上边不写GB2312，等于这里用UTF8组装，结果一样
        return msg;

    }

    public void dialerVPN(){
//        execExtFile.callCmd("c:\\windows\\vpndialer\\vpndialer.bat");
        execExtFile.callCmd("c:\\vpndialer.bat");
    }

    /**
     * 连接ADSL
     * 语法： rasdial  连接名称 username password
     * 实例： rasdial 我的宽带 hzhz1234567890 dfdfdfdfdf
     */
    public static boolean connAdsl(String adslTitle, String adslName, String adslPass) throws Exception {

        String adslCmd = "rasdial " + adslTitle + " " + adslName + " " + adslPass;
//        adslCmd = "rasdial cvpn chanchaw 7758chanchaw";
        log.info("开始建立连接：" + adslCmd);
        String tempCmd = executeCmd(adslCmd);
        //String tempCmd = executeCmd("ping www.youku.com");
        log.info("创建连接返回的信息是：" + tempCmd);
        // 判断是否连接成功
        if (tempCmd.indexOf("已连接") > 0) {
            log.info("已成功建立连接");
            return true;
        } else {
            log.info(tempCmd);
            log.info("建立连接失败");
            return false;
        }
    }

    /**
     * 断开ADSL
     */
    public static boolean cutAdsl(String adslTitle) throws Exception {
        String cutAdsl = "rasdial " + adslTitle + " /disconnect";
        String result = executeCmd(cutAdsl);

        if (result.indexOf("没有连接")!=-1){
            log.info(adslTitle + "连接不存在!");
            return false;
        } else {
            log.info("连接已断开");
            return true;
        }
    }
}
